package com.bluesky.page;

import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class PageQueryAspect {

    /**
     * 拦截mapper中的素有方法
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.bluesky..*Mapper.*(..))")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        boolean pageFlag = false;
        try{
            //遍历参数，参数中如果有 IPageQuery 类型的，则从 IPageQuery 取出分页信息，
            // 则使用 PageHelper 开启分页
            Object[] args = point.getArgs();
            for (Object arg : args) {
                if(arg instanceof IPageQuery){
                    IPageQuery pageQuery = (IPageQuery) arg;
                    PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize(), pageQuery.count());
                    pageFlag = true;
                    break;
                    /*if(pageQuery.count()){
                        pageFlag = true;
                        break;
                    }*/
                }
            }
            return point.proceed();
        }finally{
            if(pageFlag){
                // 清理分页信息
                PageHelper.clearPage();
            }
        }
    }
}